import Vue from 'vue'
import Vuex from 'vuex'
import {getProducts} from './api/shop'


Vue.use(Vuex)
let store= new Vuex.Store({
  state:{
    products:getProducts(),
    carts:[]
  },
  //同步存放
  mutations:{
    add:function(state,product){
      let index=state.carts.findIndex((cart,index)=>{
          if (cart.id === product.id) {
          return true;
        }
      });
      if (index != -1) {
        state.carts[index].num++;
      } else {
        let cart = JSON.parse(JSON.stringify(product));
        cart.num = 1;
        state.carts.push(cart);
      }
    }
  }

})
export default store;